﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Security.Cryptography;
using System.Net;
using System.IO;
using System.ComponentModel;
using System.Drawing;
using System.Net.Mail;

namespace WebRole1
{
    public partial class _Default : System.Web.UI.Page
    {
        taraService svc = new taraService();
        protected void Page_Load(object sender, EventArgs e)
        {
            //int i = svc.createNewSession(33, 5);
            //Response.Write(i.ToString());
            //svc.createNewGamePlay(3, "2", "2", "2");
            //imageByte = ReadImageFile("Screenshot.png");
            //svc.saveScreenShot(33, 5, imageByte);
            //SmtpClient MySMTPClient;
            //MailMessage myEmail;

            //MySMTPClient = new SmtpClient("smtp.gmail.com", 587);
            //MySMTPClient.Credentials = new NetworkCredential("g4ewdt@gmail.com", "inventory");
            //MySMTPClient.EnableSsl = true;
            //myEmail = new MailMessage(new MailAddress("g4ewdt@gmail.com"), new MailAddress("ashsure@hotmail.com"));
            //myEmail.Body = "Just some random text to test the email Functionality for my Azure Application";
            //myEmail.Subject = "Email from an Azure app!";
            //try
            //{
            //    MySMTPClient.Send(myEmail);
            //    Response.Write("Email Sent!");
            //}
            //catch (Exception ex)
            //{
            //    // Display Exception Details
            //    Response.Write(ex.ToString());
            //}

            //patient x = svc.retrievePatient(33);
            //Response.Write("");
            //svc.createSession(33, 10);
            //var x = 5;
            //int sum = Convert.ToInt16(x) * 2;
            //Response.Write(sum.ToString());
            //string value = "s9204433h";
            ////char first = value[3];
            ////Response.Write((Convert.ToInt16(first) * 2).ToString());
            //Response.Write(NRICValidation(value.ToString()));
            //List<EXE> x = svc.searchEXE("Bonanza");
            //foreach (EXE i in x)
            //{
            //    Response.Write(i.Uid.ToString());
            //}
            //svc.addNewPatient("lim", "chong", Convert.ToDateTime(DateTime.Now), "male", "Singapore", "tampines", "333333", "2222222", "222222", "sds@sds", "heny", "Picture2.png", new byte[1541065], "sdsd");
            //string y = "";
            //string z = "";
            //////for (int i = 0; i < 2; i++)
            //////{

            ////try
            ////{

            //try
            //{
            //    byte[] x = svc.retrieveImage("http://tarastorage.blob.core.windows.net/tarastorage/Untitled.png");
            //    y += x.ToString();
            //}
            //catch (Exception ex)
            //{
            //    z += ex.ToString();
            //}

            //    byte[] x = svc.retrieveImage("http://tarastorage.blob.core.windows.net/tarastorage/Untitled.png");
            //    y += x.ToString();

            //}
            //catch (Exception ex)
            //{
            //    z += ex.ToString();
            //}
            //}
            //Response.Write(y.ToString() + "and" + z.ToString());
            //img = BytesToBitmap(x);
            //System.IO.MemoryStream ms = new System.IO.MemoryStream(x);
            //ms.Position = 0;
            //System.Drawing.Bitmap b = new System.Drawing.Bitmap(ms);

            //ImageConverter ic = new ImageConverter();
            //System.Drawing.Image imgd = (System.Drawing.Image)ic.ConvertFrom(x);
            
            //ts.addNewPatient("lim", "chong", "mr", DateTime.Today, "m", "singapore", "tampines", "ave", "3433432", "93433343", "3123234", "@hotmail.com", "heny", "test", new byte[2322], "S2324333");
            //Response.Write("HAHA" + Login("test", Hash("test")));
            //Response.Write(svc.addAndUpdateJointProblem(1, 54, 1));
            //byte[] x = svc.retrieveImage("http://tarastorage.blob.core.windows.net/tarastorage/Untitled.png");
            //Response.Write("test" + x.ToString());

            //svc.sendEmail("sds", "ashsure@hotmail.com", "Test");
            //List<KeyValuePair<int, int>> jointList = new List<KeyValuePair<int, int>>();
            //jointList = svc.getAllJoint(33);
            //string x = "";
            //foreach (KeyValuePair<int, int> temp in jointList)
            //{
            //        //Modify the current jointList
            //        x += temp.Key.ToString() + " and " + temp.Value.ToString() + "\n";
            //        //MainPage.jointList[index] = new KeyValuePair<int, int>(temp.Key, Convert.ToInt16(tbxSeverity.Text));
            //        //index++;
            //        //editToJointList = true;
            //        //break;                
            //}
            //Response.Write(x.ToString());

            //svc.retrieveAllTreatment();
            //int uid = Login("S1213568G", Hash("GEzaKbAe"));
            //Response.Write(uid.ToString());

            //svc.sendEmail("HAHA", "ashsure@hotmail.com", "232");

            //MailMessage mailMsg = new MailMessage();
            ////mailMsg.From = new MailAddress("g4ewdt@gmail.com.com");
            //mailMsg.To.Add("ashsure@hotmail.com");
            //mailMsg.Subject = "Test subject";
            //mailMsg.IsBodyHtml = true;
            //mailMsg.BodyEncoding = Encoding.UTF8;
            //mailMsg.Body = "This email is sent from asp.net code";
            //mailMsg.Priority = MailPriority.Normal;
            //// Smtp configuration
            //SmtpClient client = new SmtpClient();
            ////client.Credentials = new NetworkCredential("g4ewdt@gmail.com", "inventory");
            //client.Port = 587; //or use 465            
            //client.Host = "smtp.gmail.com";
            //client.EnableSsl = true;
            //object userState = mailMsg;
            //try
            //{
            //    //you can also call client.Send(msg)
            //    client.SendAsync(mailMsg, userState);
            //}
            //catch (SmtpException)
            //{
            //    //Catch errors...
            //}
        }

        byte[] imageByte;
        private byte[] ReadImageFile(string PostedFileName)
        {
            try
            {
                FileStream fs = new FileStream(PostedFileName, FileMode.Open, FileAccess.Read);

                BinaryReader br = new BinaryReader(fs);

                byte[] image = br.ReadBytes((int)fs.Length);

                br.Close();

                fs.Close();

                return image;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void sendEmail(string lastName, string email, string password)
        {
            string body = "Your new password is " + password;
            MailMessage MyMailMessage = new MailMessage();
            MyMailMessage.From = new MailAddress("g4ewdt@gmail.com");
            MyMailMessage.To.Add(email.Trim());

            MyMailMessage.Subject = "New Password";
            MyMailMessage.IsBodyHtml = true;
            MyMailMessage.Body = "<table><tr><td>" + "Dear " + lastName + ", <br>The following is your password to TARA. <br> Your password: " + password + "<br> Do note that passwords are case sensitive, enter them as what is given to you. If you copy and paste your password, make sure you did not copy extra space in front or after the password. <br> Please change your password immediately after login. Keep your new password safely for your future logins. <br>Should you encounter any problem with regards to your account, please contact our helpdesk support at g4ewdt@gmail.com, stating clearly your problem. <br> Thank you. <br> Account Support Divison</table></tr></td>";

            SmtpClient SMTPServer = new SmtpClient("smtp.gmail.com");
            SMTPServer.Port = 587;
            SMTPServer.Credentials = new System.Net.NetworkCredential("g4ewdt@gmail.com", "inventory"); //need a password
            SMTPServer.EnableSsl = true;
        }

        public bool NRICValidation(string nric)
        {
            nric = nric.ToUpper();
            int first = nric[0];
            int second = nric[1];
            int third = nric[2];
            int fourth = nric[3];
            int fifth = nric[4];
            int sixth = nric[5];
            int seventh = nric[6];
            int eighth = nric[7];
            int nineth = nric[8];

            int sum = Convert.ToInt16(second - '0') * 2 + Convert.ToInt16(third - '0') * 7 + Convert.ToInt16(fourth - '0') * 6 + Convert.ToInt16(fifth - '0') * 5 + Convert.ToInt16(sixth - '0') * 4 + Convert.ToInt16(seventh - '0') * 3 + Convert.ToInt16(eighth - '0') * 2;
            int reminder = sum % 11;
            if (first.Equals('S') || first.Equals('T'))
            {
                switch (reminder)
                {
                    case 0:
                        if (nineth.Equals('J'))
                        {
                            return true;
                        }
                        break;
                    case 1:
                        if (nineth.Equals('Z'))
                        {
                            return true;
                        }
                        break;
                    case 2:
                        if (nineth.Equals('I'))
                        {
                            return true;
                        }
                        break;
                    case 3:
                        if (nineth.Equals('H'))
                        {
                            return true;
                        }
                        break;
                    case 4:
                        if (nineth.Equals('G'))
                        {
                            return true;
                        }
                        break;
                    case 5:
                        if (nineth.Equals('F'))
                        {
                            return true;
                        }
                        break;
                    case 6:
                        if (nineth.Equals('E'))
                        {
                            return true;
                        }
                        break;
                    case 7:
                        if (nineth.Equals('D'))
                        {
                            return true;
                        }
                        break;
                    case 8:
                        if (nineth.Equals('C'))
                        {
                            return true;
                        }
                        break;
                    case 9:
                        if (nineth.Equals('B'))
                        {
                            return true;
                        }
                        break;
                    case 10:
                        if (nineth.Equals('A'))
                        {
                            return true;
                        }
                        break;
                }
            }
            else if (first.Equals('F') || first.Equals('G'))
            {
                sum += 4;
                reminder = sum % 11;
                switch (reminder)
                {
                    case 0:
                        if (nineth.Equals('X'))
                        {
                            return true;
                        }
                        break;
                    case 1:
                        if (nineth.Equals('W'))
                        {
                            return true;
                        }
                        break;
                    case 2:
                        if (nineth.Equals('U'))
                        {
                            return true;
                        }
                        break;
                    case 3:
                        if (nineth.Equals('T'))
                        {
                            return true;
                        }
                        break;
                    case 4:
                        if (nineth.Equals('R'))
                        {
                            return true;
                        }
                        break;
                    case 5:
                        if (nineth.Equals('Q'))
                        {
                            return true;
                        }
                        break;
                    case 6:
                        if (nineth.Equals('P'))
                        {
                            return true;
                        }
                        break;
                    case 7:
                        if (nineth.Equals('N'))
                        {
                            return true;
                        }
                        break;
                    case 8:
                        if (nineth.Equals('M'))
                        {
                            return true;
                        }
                        break;
                    case 9:
                        if (nineth.Equals('L'))
                        {
                            return true;
                        }
                        break;
                    case 10:
                        if (nineth.Equals('K'))
                        {
                            return true;
                        }
                        break;
                }
            }
            return false;
        }


        public static Bitmap BytesToBitmap(byte[] byteArray)
        {

            using (MemoryStream ms = new MemoryStream(byteArray))
            {
                Bitmap img = (Bitmap)System.Drawing.Image.FromStream(ms);
                return img;
            }

        }

        public void byteArrayToImage(byte[] byteArrayIn)
        {
            System.Drawing.Image newImage;

            //string strFileName = GetTempFolderName() + strFile_Name;

            using (MemoryStream stream = new MemoryStream(byteArrayIn))
            {
                newImage = System.Drawing.Image.FromStream(stream);

                newImage.Save("s");

                img.Attributes.Add("src", "s");
                //Page_Load(null, null);
            }
        }

        //private string Hash(string ToHash)
        //{
        //    // First we need to convert the string into bytes, which means using a text encoder.
        //    Encoder enc = System.Text.Encoding.ASCII.GetEncoder();

        //    // Create a buffer large enough to hold the string
        //    byte[] data = new byte[ToHash.Length];
        //    enc.GetBytes(ToHash.ToCharArray(), 0, ToHash.Length, data, 0, true);

        //    SHA1 sha1 = new SHA1CryptoServiceProvider();
        //    byte[] result = sha1.ComputeHash(data);

        //    return BitConverter.ToString(result).Replace("-", "");
        //}

        //private string Login(string username, string password)
        //{
        //    string Key, ToHash;
        //    string Token = svc.GetToken();
        //    ToHash = username + "|" + password + "|" + Token;
        //    Key = Hash(ToHash) + "|" + username + "|I would like to log this string in a DB";

        //    return svc.DocUseService(Key);
        //}

        private string Hash(string ToHash)
        {
            // First we need to convert the string into bytes, which means using a text encoder.
            Encoder enc = System.Text.Encoding.ASCII.GetEncoder();

            // Create a buffer large enough to hold the string
            byte[] data = new byte[ToHash.Length];
            enc.GetBytes(ToHash.ToCharArray(), 0, ToHash.Length, data, 0, true);

            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] result = sha1.ComputeHash(data);

            return BitConverter.ToString(result).Replace("-", "");
        }

        private int Login(string username, string password)
        {
            string Key, ToHash;
            string Token = svc.GetToken();
            ToHash = username + "|" + password + "|" + Token;
            Key = Hash(ToHash) + "|" + username + "|I would like to log this string in a DB";

            return svc.PatientUseService(Key);
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            taraService asd = new taraService();
            asd.createNewSession(61, 5);
        }
    }
}